let _Vue;

class VueRouter {
    constructor(options) {
        this.mode = options.mode || 'hash';
        this.routes = options.routes || {};
        Vue.util.defineReactive(this, 'current', '/');
        this.init();
    }

    init(){
        if (this.mode === 'hash') {
            window.addEventListener('load', () => {
                this.current = window.location.hash.slice(1);
            });

            window.addEventListener('hashchange', () => {
                this.current = window.location.hash.slice(1);
            });
        } else {

        }
    }

    static install(Vue, params) {
        _Vue = Vue;

        Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    this.$router = this.$options.router;
                } else {
                    this.$router = this.$parent && this.$parent.$router;
                }
            }
        });

        _Vue.component('router-link', {
            props: {
              to: {
                  type: String,
                  required: true
              }
            },
            render(h) {
                return h('a', {attrs: {href: this.to}}, this.$slots.default);
            }
        });

        _Vue.component('router-view', {
            render(h) {
                // 需要拿到component配置选项
                let current = this.$router.current;
                let routes = this.$router.routes;
                let com = routes.find(item => current === item.path);
                return h(com.component);
            }
        });
    }
}
